package com.woniuxy.handler.predicate;

import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.http.server.PathContainer;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.function.Predicate;

/**
 * @Author: 马宇航
 * @Todo: 自定义断言，通过价格来进行放行路由
 * @DateTime: 25/08/05/星期二 17:01
 * @Component: 成都蜗牛学苑
 **/
@Component
public class BetweenPriceRoutePredicateFactory extends AbstractRoutePredicateFactory<BetweenPriceRoutePredicateFactory.Config> {

    public BetweenPriceRoutePredicateFactory() {
        super(Config.class);
    }
    //配置对应的 顺序，第一个是startPrice，第二个是endPrice
    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("startPrice","endPrice");
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        //内部类配置yml中取出的0 和200
        int startPriceConfig = config.getStartPrice();
        int endPriceConfig = config.getEndPrice();
        return new Predicate<ServerWebExchange>() {
            @Override
            public boolean test(ServerWebExchange exchange) {
                //通过url参数，获取开始和结束的价格范围
//                MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams();
                //restFul方案
                if (exchange.getRequest().getMethod().name().equals("GET")&&exchange.getRequest().getPath().value().length() != 10) {
                    String startPriceString = exchange.getRequest().getPath().subPath(7, 8).value();
                    String endPriceString = exchange.getRequest().getPath().subPath(9, 10).value();
                    int startPrice = Integer.parseInt(Objects.requireNonNull(startPriceString));
                    int endPrice = Integer.parseInt(Objects.requireNonNull(endPriceString));
                    if(startPrice>=startPriceConfig && endPrice <= endPriceConfig){
                        return true;
                    }else {
                        return false;
                    }
                }else {
                    return true;
                }

            }
        };
    }
    //对应配置后面的值
    public static class Config {
        private int startPrice;
        private int endPrice;

        public int getStartPrice() {
            return startPrice;
        }

        public void setStartPrice(int startPrice) {
            this.startPrice = startPrice;
        }

        public int getEndPrice() {
            return endPrice;
        }

        public void setEndPrice(int endPrice) {
            this.endPrice = endPrice;
        }
    }
}
